import React from 'react'
// 引入编辑器组件
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'
import { ContentUtils } from 'braft-utils'
import './index.less'
import AliyunOSSUpload from '../AliyunOSSUpload'
// import { Button } from 'antd'
// import { UploadOutlined } from '@ant-design/icons'

export default class EditorDemo extends React.Component {

  state = {
    // 创建一个空的editorState作为初始值
    editorState: BraftEditor.createEditorState(this.props.content ? this.props.content : null)
  }

  controls: string[] = [
    'undo', 'redo', 'separator',
    'font-size', 'line-height', 'letter-spacing', 'separator',
    'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
    'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator',
    'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
    'link', 'separator', 'hr', 'separator', 'fullscreen',
    'clear', 'separator'
  ]

  async componentDidMount() {
    /* // 假设此处从服务端获取html格式的编辑器内容
    const htmlContent = await fetchEditorContent()
    // 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
    this.setState({
        editorState: BraftEditor.createEditorState(htmlContent)
    }) */
  }

  /* submitContent = async () => {
      // 在编辑器获得焦点时按下ctrl+s会执行此方法
      // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
      const htmlContent = this.state.editorState.toHTML()
      const result = await saveEditorContent(htmlContent)
  } */

  handleEditorChange = (editorState) => {
    this.setState({ editorState })
    if (!editorState.isEmpty()) {
      this.props.setDetails(editorState.toHTML());
    } else {
      this.props.setDetails("");
    }
  }

  insertImageUrl = url => {
    this.setState({
      editorState: ContentUtils.insertMedias(this.state.editorState, [{
        type: 'IMAGE',
        url,
      }])
    })
  }

  render() {
    const { editorState } = this.state
    const extendControls: object[] = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <AliyunOSSUpload
            accept='image/*'
            showUploadList={false}
            insertImageUrl={this.insertImageUrl}
          >
            <button
              type="button"
              className="control-item button upload-button"
              data-title="插入图片"
            >
              插入图片
            </button>
          </AliyunOSSUpload>
        )
      }
    ]

    return (
      <div className="my-editor">
        <BraftEditor
          value={editorState}
          onChange={this.handleEditorChange}
          contentStyle={{ height: "200px" }}
          controls={this.controls}
          extendControls={extendControls}
        // onSave={this.submitContent}
        />
      </div>
    )

  }

}